//
//  LCYHttpTool.m
//  DFace
//
//  Created by lcy on 14-8-20.
//  Copyright (c) 2014年 lcy. All rights reserved.
//


#import "LCYHttpTool.h"
#import "AFNetworking.h"
#import "LCYHTTPRequestOperationManager.h"
#import <objc/runtime.h>

static NSString * const LCYNetAPIBaseURLString = @"https://42.121.79.210";

@interface LCYHttpTool ()
@property (nonatomic, retain) LCYHTTPRequestOperationManager *mgr;
@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFHTTPRequestOperation *af_imageRequestOperation;
@end

@implementation LCYHttpTool

- (void)_singletonInit
{
    _mgr = [[LCYHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:[self getIpServerAddress]]];
}

+ (LCYHttpTool *)sharedManager
{
    static LCYHttpTool *_sharedTool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedTool = [[self alloc] init];
        [_sharedTool _singletonInit];
    });
    
    return _sharedTool;
}

- (void)get:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    //发送Get请求
    [_mgr GET:[self urlWithStr:url] parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*responseObj) {
        if (success) {
            success(responseObj);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    //2.发送Post请求
    [_mgr POST:[self urlWithStrs:url] parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*responseObj) {
        if (success) {
            success(responseObj);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

- (AFHTTPRequestOperation *)LCYRequestOperation {
    return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, @selector(af_imageRequestOperation));
}

- (void)cancelPost:(NSString *)url
{
    [self.af_imageRequestOperation cancel];
    self.af_imageRequestOperation = nil;
}

#pragma mark - URL

- (NSString *)getIpServerAddress
{
    return @"https://42.121.79.210";
}

-(NSString *)baseURL
{
    return @"https://api.app.net/";
}

-(NSString*)urlWithStr:(NSString *)url
{
    NSString *urlString = [NSString stringWithFormat:@"%@/%@",[self getIpServerAddress],url];
    return urlString;
}

-(NSString*)urlWithStrs:(NSString *)url
{
    NSString *urlString = [NSString stringWithFormat:@"%@/%@",[self baseURL],url];
    return urlString;
}

@end
